/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.security;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.security.Users;
import src.domain.security.UsersConfig;
import src.services.finance.BankModel;
import src.services.security.UgroupModel;
import src.services.security.UsersModel;
import src.services.system.BranchModel;
import src.util.Messager;
import src.util.Utils;

/**
 *
 * @author Yusup Jauhari Shandi <chan at In.Visi Forever!>
 */

@ManagedBean
@SessionScoped
public class UsersBean implements Serializable{
    private List<Users> users;
    private List<SelectItem> avaibleBranch;
    private List<SelectItem> avaibleGroup,avbBank;
    private Users selectedData, insertedData;
    private boolean editMode;
    private boolean passwordChange=false;
    private BankModel bankHelper;

    public UsersBean() {
        UsersModel helper = new UsersModel();
        this.users = helper.findAll(null);
        
        BranchModel branchs = new BranchModel();
        this.avaibleBranch = branchs.listAll();
        
        UgroupModel groups = new UgroupModel();
        this.bankHelper = new BankModel();
        this.avaibleGroup = groups.listAll();
        this.avbBank = bankHelper.listAll();
        this.insertedData = null;
        this.selectedData = null;
        
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public Users getInsertedData() {
        return insertedData;
    }

    public void setInsertedData(Users insertedData) {
        this.insertedData = insertedData;
    }

    public Users getSelectedData() {
        return selectedData;
    }

    public void setSelectedData(Users selectedData) {
        this.selectedData = selectedData;
    }

    public List<Users> getUsers() {
        return users;
    }

    public void setUsers(List<Users> users) {
        this.users = users;
    }

    public List<SelectItem> getAvaibleBranch() {
        return avaibleBranch;
    }

    public List<SelectItem> getAvaibleGroup() {
        return avaibleGroup;
    }

    public List<SelectItem> getAvbBank() {
        return avbBank;
    }
    
     public void handleClose(CloseEvent event) {
        this.selectedData = null;
        this.insertedData = null;
        this.editMode = true;      
    }
    
    public void newData() {  
        this.selectedData = null;
        this.editMode = false;
        this.insertedData = new Users();
    
       // FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "New Data");  
      //  FacesContext.getCurrentInstance().addMessage(null, msg); 
    }
    
     public void openData() {
        this.editMode = true;
        this.insertedData = Users.clone(selectedData);        
    }
     
    public void passwordIsChange(){
        this.passwordChange = true;
    }
     
    public void prepareChangePasswd(){
        FacesContext fc = FacesContext.getCurrentInstance();        
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
       // Map<String, Object> filters = new HashMap<>();
       // filters.put("userId = ", );
        UsersModel helper = new UsersModel();
        editMode = true;
        this.insertedData = helper.getById((Integer)session.getAttribute("userid"));


    }
    
    public void save() {
        
        RequestContext context = RequestContext.getCurrentInstance();  
        
        boolean success;  
             
        UsersModel helper = new UsersModel();
        
        UsersConfig usersConfig;
        if (insertedData.getSavBankId()==-1) insertedData.setSavBankId(null);
        if (!editMode){
            usersConfig = new UsersConfig();
            usersConfig.setUsers(this.insertedData);
             this.insertedData.setUsersConfig(usersConfig); 
        }
        //if (usersConfig.getThemes().isEmpty()){
          //      usersConfig.setThemes("home");
        //}   
       
        
        
        //data.setUsersConfig(usersConfig);
        if (passwordChange)
            this.insertedData.setPassword(setMd5(this.insertedData.getPassword()));
        success = helper.saveData(this.insertedData);
        if (success==true) {
            if (this.editMode==false) this.users.add(insertedData);
            else {
                int i = users.indexOf(selectedData);
                if (i <= users.size()) users.set(i, Users.clone(insertedData));
            }
            editMode = true;
            
        } else {
            if (this.editMode==false) insertedData.setUserId(null);
        }
        
       
        //msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info: ", data.getUsersName()); 
        Messager.showSaveUpdateStatus(success);        
        context.addCallbackParam("success", success); 
    }
    
    public void changePasswd(){
        RequestContext context = RequestContext.getCurrentInstance();          
        boolean success=false;  
        
        Messager.showSaveUpdateStatus(success);        
        context.addCallbackParam("success", success); 
    }
    
    public void delete() {
        
        RequestContext context = RequestContext.getCurrentInstance();  
        FacesMessage msg = null;
        boolean success = true;  
       // msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info: ", this.selectedData.getUsersName()); 
        
        UsersModel helper = new UsersModel();
        success = helper.deleteData(this.selectedData);
        
        if (success) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Penghapusan berhasil.");
           
            this.users.remove(this.selectedData);
            //this.selectedData = null;
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "Penghapusan tidak berhasil.");  
        }
               
        if(!success) Messager.showDeleteStatusConstaint(success);
        context.addCallbackParam("success", success);   
    }  
    
    
    public String setMd5(String param) {
        byte[] defaultBytes = param.getBytes();
            try{
                MessageDigest algorithm = MessageDigest.getInstance("MD5");
                algorithm.reset();
                algorithm.update(defaultBytes);
                byte messageDigest[] = algorithm.digest();

                StringBuffer hexString = new StringBuffer();
                for (int i=0;i<messageDigest.length;i++) {
                        hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
                }
                //String foo = messageDigest.toString();
                //System.out.println("sessionid "+passwd+" md5 version is "+hexString.toString());
                param=hexString+"";
            }catch(NoSuchAlgorithmException nsae){

            }
        
        return  param;
    }
    
    public String findGroupName(Integer id) {
        String nama = "";
        if (id!=null && !id.equals(0)) {
            int idx=0;
            boolean found=false;
            while (idx<avaibleGroup.size() && !found) {
                SelectItem it = avaibleGroup.get(idx);
                found = id.equals(it.getValue()) ? true:false;
                if (found) nama = it.getLabel();
                idx++;
            }
        }
        return nama;
    }
    
    public String selectItemValueOf(List<SelectItem> avblList, Integer id) {
        return (String) Utils.selectItemValueOf(avblList, id);
    }
    
    public String findBranchName(Integer id) {
        String nama = "";
        if (id!=null && !id.equals(0)) {
            int idx=0;
            boolean found=false;
            while (idx<avaibleBranch.size() && !found) {
                SelectItem it = avaibleBranch.get(idx);
                found = id.equals(it.getValue()) ? true:false;
                if (found) nama = it.getLabel();
                idx++;
            }
        }
        return nama;
    }
}
